class BluetoothService {
  constructor() {
    // 与移动端相同的 UUID
    this.SERVICE_UUID = "0000FFE0-0000-1000-8000-00805F9B34FB"
    this.CONTROL_CHARACTERISTIC_UUID = "0000FFE1-0000-1000-8000-00805F9B34FB"
    this.NOTIFY_CHARACTERISTIC_UUID = "0000FFE2-0000-1000-8000-00805F9B34FB"
    
    this.device = null
    this.server = null
    this.service = null
    this.controlCharacteristic = null
    this.notifyCharacteristic = null
    this.notificationCallback = null
  }

  // 检查浏览器是否支持 Web Bluetooth
  checkAvailability() {
    if (!navigator.bluetooth) {
      throw new Error('此浏览器不支持 Web Bluetooth')
    }
  }

  // 连接设备
  async connect() {
    try {
      // 请求选择设备
      this.device = await navigator.bluetooth.requestDevice({
        filters: [
          {
            name: 'BlueRecord'  // 匹配移动端广播的设备名
          },
          {
            services: [this.SERVICE_UUID]  // 匹配服务 UUID
          }
        ]
      })

      // 监听设备断开连接
      this.device.addEventListener('gattserverdisconnected', this.onDisconnected.bind(this))

      // 连接到设备
      this.server = await this.device.gatt.connect()

      // 获取服务
      this.service = await this.server.getPrimaryService(this.SERVICE_UUID)

      // 获取特征值
      this.controlCharacteristic = await this.service.getCharacteristic(this.CONTROL_CHARACTERISTIC_UUID)
      this.notifyCharacteristic = await this.service.getCharacteristic(this.NOTIFY_CHARACTERISTIC_UUID)

      // 启用通知
      await this.notifyCharacteristic.startNotifications()
      this.notifyCharacteristic.addEventListener('characteristicvaluechanged', this.onNotificationReceived.bind(this))

      return true
    } catch (error) {
      console.error('连接失败:', error)
      throw error
    }
  }

  // 断开连接
  async disconnect() {
    if (this.device && this.device.gatt.connected) {
      await this.device.gatt.disconnect()
    }
  }

  // 设置通知回调
  setNotificationCallback(callback) {
    this.notificationCallback = callback
  }

  // 处理接收到的通知
  onNotificationReceived(event) {
    if (this.notificationCallback) {
      this.notificationCallback(event)
    }
  }

  // 发送命令
  async sendCommand(command) {
    if (!this.controlCharacteristic) {
      throw new Error('未连接到设备')
    }

    console.log('发送命令:', command)
    const encoder = new TextEncoder()
    const data = encoder.encode(command)
    await this.controlCharacteristic.writeValue(data)
  }

  // 开始录制
  async startRecording() {
    console.log('发送开始录制命令')
    await this.sendCommand('START_RECORDING')
  }

  // 停止录制
  async stopRecording() {
    console.log('发送停止录制命令')
    await this.sendCommand('STOP_RECORDING')
  }

  // 处理设备断开连接
  onDisconnected() {
    console.log('设备已断开连接')
    this.device = null
    this.server = null
    this.service = null
    this.controlCharacteristic = null
    this.notifyCharacteristic = null
  }
}

export default new BluetoothService() 